package com.stationbuilding.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.stationbuilding.MyApplication;
import com.stationbuilding.R;
import com.stationbuilding.adapter.SelectListAdapter;
import com.stationbuilding.api.RetrofitManager;
import com.stationbuilding.bean.DictBean;
import com.stationbuilding.bean.DictListBean;
import com.stationbuilding.bean.ProcedureBean;
import com.stationbuilding.bean.ProcedureListBean;
import com.stationbuilding.bean.QuestionTypeBean;
import com.stationbuilding.bean.QuestionTypeListBean;
import com.stationbuilding.bean.SubdivisionBean;
import com.stationbuilding.bean.SubdivisionListBean;
import com.stationbuilding.bean.UserBean;
import com.stationbuilding.constants.Constants;
import com.stationbuilding.utils.DialogUtils;
import com.stationbuilding.utils.PreferenceHelper;
import com.zhy.tree.bean.Node;
import com.zhy.tree.bean.TreeListViewAdapter;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class TreeSelectFragment extends Fragment {

    private View view;
    private SelectListAdapter selectListAdapter;
    private Dialog dialog;//加载提示
    private LinearLayout emptyView;//空试图
    private List<DictBean> dictList = new ArrayList<>();
    private List<SubdivisionBean> treeList = new ArrayList<>();
    private List<QuestionTypeBean> questionTypeList = new ArrayList<>();
    private List<ProcedureBean> procedureList = new ArrayList<>();
    private int id;
    private ListView listView;
    private Node node;
    private String token = PreferenceHelper.getInstance(getActivity()).getToken();
    private String ifdCode;
    private TreeListViewAdapter.OnTreeNodeClickListener onTreeNodeClickListener = new TreeListViewAdapter.OnTreeNodeClickListener() {
        @Override
        public void onClick(Node node, int position) {
            setNode(node);
            selectListAdapter.setSelectedPosition(position);
            selectListAdapter.notifyDataSetChanged();
            if (id == R.id.subdivision) {
                ifdCode = treeList.get(position).getIfdCode();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_tree_select, container, false);
        id = getArguments().getInt("id");
        ifdCode = getArguments().getString("ifdCode");
        init();
        return view;
    }

    public Node getNode() {
        return node;
    }

    public void setNode(Node node) {
        this.node = node;
    }

    /**
     * 初始化操作
     */
    private void init() {
        emptyView = (LinearLayout) view.findViewById(R.id.empty_view);
        listView = (ListView) view.findViewById(R.id.list);

        RetrofitManager.getInstance().setOnInternetListener(new RetrofitManager.OnInternetListener() {
            @Override
            public void internetListener() {
                emptyView.setVisibility(View.VISIBLE);
            }
        });
        if (id == R.id.question_type) {
            loadQuestionTypeList();
        } else if (id == R.id.question_level) {
            loadLevelList();
        } else if (id == R.id.subdivision) {
            loadSubdivisionList();
        } else if (id == R.id.procedure) {
            loadProcedureList();
        }
    }

    /**
     * 设置选择结果
     */
    public void setResult() {
        if (node == null) {
            if (id == R.id.question_type) {
                Toast.makeText(getActivity(), "请选择问题类型！", Toast.LENGTH_SHORT).show();
            } else if (id == R.id.question_level) {
                Toast.makeText(getActivity(), "请选择问题级别！", Toast.LENGTH_SHORT).show();
            } else if (id == R.id.subdivision) {
                Toast.makeText(getActivity(), "请选择分部分项！", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("id", node.getId());
        intent.putExtra("name", node.getName());
        if (id == R.id.question_type) {
            if (node.isLeaf()) {
                setParentIdAndName(node, intent);
                setOtherProperty(node, intent);
            } else {
                Toast.makeText(getActivity(), "只能选择最后一层节点！", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (id == R.id.subdivision) {
            intent.putExtra("ifdCode", ifdCode);
        }
        getActivity().setResult(Activity.RESULT_OK, intent);
        getActivity().finish();
    }

    /**
     * 设置选择结果的父节点
     */
    private void setParentIdAndName (Node node, Intent intent) {
        Node parentNode = node.getParent();
        if (parentNode != null) {
            String id = intent.getStringExtra("id");
            String name = intent.getStringExtra("name");
            id = parentNode.getId() + Constants.COMMA + id;
            name = parentNode.getName() + Constants.ARROW_RIGHT + name;
            intent.putExtra("id", id);
            intent.putExtra("name", name);
            setParentIdAndName(parentNode, intent);
        }
    }

    /**
     * 设置其他属性
     */
    private void setOtherProperty (Node node, Intent intent) {
        for (QuestionTypeBean questionTypeBean : questionTypeList) {
            if (questionTypeBean.getId().equals(node.getId())) {
                intent.putExtra("measures", questionTypeBean.getMeasures());
                intent.putExtra("score", questionTypeBean.getScore());
                intent.putExtra("minScore", questionTypeBean.getMinScore());
                intent.putExtra("maxScore", questionTypeBean.getMaxScore());
                break;
            }
        }
    }

    /**
     * 问题类型数据加载
     */
    private void loadQuestionTypeList() {
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().getAllQuestionTypeList(token, Constants.QUESTION_TYPE_SAFE), new Observer<QuestionTypeListBean>() {
            @Override
            public void onComplete() {
                DialogUtils.closeDialog(dialog);
            }
            @Override
            public void onError(Throwable e) {
                DialogUtils.closeDialog(dialog);
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                dialog = DialogUtils.createLoadingDialog(getActivity(), Constants.LOADING);
            }
            @Override
            public void onNext(QuestionTypeListBean questionTypeListBean) {
                questionTypeList.addAll(questionTypeListBean.getQuestionTypeList());
                emptyView.setVisibility(View.GONE);
                try {
                    selectListAdapter = new SelectListAdapter<>(listView, MyApplication.getContext(), questionTypeList, 0, null);
                    selectListAdapter.setOnTreeNodeClickListener(onTreeNodeClickListener);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                listView.setAdapter(selectListAdapter);
            }
        });
    }

    /**
     * 问题等级数据加载
     */
    private void loadLevelList() {
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().getDictListByPid(token, Constants.DICT_ID_QUESTION_LEVEL), new Observer<DictListBean>() {
            @Override
            public void onComplete() {
                DialogUtils.closeDialog(dialog);
            }
            @Override
            public void onError(Throwable e) {
                DialogUtils.closeDialog(dialog);
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                dialog = DialogUtils.createLoadingDialog(getActivity(), Constants.LOADING);
            }
            @Override
            public void onNext(DictListBean dictListBean) {
                dictList = dictListBean.getDictList();
                emptyView.setVisibility(View.GONE);
                try {
                    selectListAdapter = new SelectListAdapter<>(listView, MyApplication.getContext(), dictList, 0, null);
                    selectListAdapter.setOnTreeNodeClickListener(onTreeNodeClickListener);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                listView.setAdapter(selectListAdapter);
            }
        });
    }

    /**
     * 分部分项数据加载
     */
    private void loadSubdivisionList() {
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().getSubdivisionList(token), new Observer<SubdivisionListBean>() {
            @Override
            public void onComplete() {
                DialogUtils.closeDialog(dialog);
            }
            @Override
            public void onError(Throwable e) {
                DialogUtils.closeDialog(dialog);
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                dialog = DialogUtils.createLoadingDialog(getActivity(), Constants.LOADING);
            }
            @Override
            public void onNext(SubdivisionListBean subdivisionListBean) {
                treeList.addAll(subdivisionListBean.getFlowSectionEntities());
                emptyView.setVisibility(View.GONE);
                try {
                    selectListAdapter = new SelectListAdapter<>(listView, MyApplication.getContext(), treeList, 0, null);
                    selectListAdapter.setOnTreeNodeClickListener(onTreeNodeClickListener);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                listView.setAdapter(selectListAdapter);
            }
        });
    }

    /**
     * 当前工序数据加载
     */
    private void loadProcedureList() {
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().getProcedureList(token, ifdCode), new Observer<ProcedureListBean>() {
            @Override
            public void onComplete() {
                DialogUtils.closeDialog(dialog);
            }
            @Override
            public void onError(Throwable e) {
                DialogUtils.closeDialog(dialog);
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                dialog = DialogUtils.createLoadingDialog(getActivity(), Constants.LOADING);
            }
            @Override
            public void onNext(ProcedureListBean procedureListBean) {
                procedureList.addAll(procedureListBean.getEntityDecomposeEntities());
                emptyView.setVisibility(View.GONE);
                try {
                    selectListAdapter = new SelectListAdapter<>(listView, MyApplication.getContext(), procedureList, 0, null);
                    selectListAdapter.setOnTreeNodeClickListener(onTreeNodeClickListener);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                listView.setAdapter(selectListAdapter);
            }
        });
    }
}
